from django.contrib.auth.backends import ModelBackend
import re
from .models import User
def jwt_response_payload_handler(token, user=None, request=None):
    """
    重写jwt登录试图的构造响应数据函数，多追加 user_id和username
    :param token:
    :param user:
    :param request:
    :return:
    """
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }


def get_user_by_account(account):
    """
    通过传入的账号获取user模型对象
    :param account: 手机号或者用户名
    :return: user或None
    """
    try:
        if re.match(r'1[3-9]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user



class UsernameMobileAuthBackend(ModelBackend):
    """
    修改django的认证类，为了实现多账号登录
    """
    def authenticate(self, request, username=None, password=None, **kwargs):
        #获取user
        user = get_user_by_account(username)

        if user and user.check_password(password):

            return user


